package edu.whcp.comp2301.dao.impl;

import edu.whcp.comp2301.dao.UserDao;
import edu.whcp.comp2301.mapper.UserMapper;
import edu.whcp.comp2301.pojo.User;
import edu.whcp.comp2301.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDaoImpl implements UserDao {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public User userLogin(String username, String password) {
        User user=userMapper.login(username);
        password=PasswordUtil.hashPassword(password,user.getSalt());
        if(user.getPassword().equals(password)){
            return user;
        }

        return null;
    }

    @Override
    public List<User> getUser(String id) {
        return userMapper.getUser(id);
    }

    @Override
    public void addUser(User user) {
        String salt= PasswordUtil.generateSalt();
        user.setSalt(salt);
        user.setPassword(PasswordUtil.hashPassword(user.getPassword(),salt));
        userMapper.addUser(user);
    }

    @Override
    public Integer delUser(String id) {
        return userMapper.delUser(id);
    }

    @Override
    public void alterUser(User user) {
        if(user.getPassword()!=null) {
            String salt = PasswordUtil.generateSalt();
            user.setSalt(salt);
            user.setPassword(PasswordUtil.hashPassword(user.getPassword(), salt));
        }
        userMapper.alterUser(user);
    }

    @Override
    public User userPageLogin(String username, String password) {
        User user=userMapper.loginPage(username);
        String salt=user.getSalt();
        password=PasswordUtil.hashPassword(password,salt);
        if(user.getPassword().equals(password)){
            return user;
        }
        return null;
    }
}
